#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
    int listen_fd,accept_fd,flag;
    struct sockaddr_in my_addr,remote_addr;
    if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        perror("create socket error");
        exit(1);
    }
    if (setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR
                    ,(char *)&flag,sizeof(flag)) == -1){
        perror("setsockopt error");
    }
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(3389);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(my_addr.sin_zero), 8);
    if (bind(listen_fd, (struct sockaddr *)&my_addr,
                sizeof(struct sockaddr_in)) == -1) {
        perror("bind error");
        exit(1);
    }
    if (listen(listen_fd,1) == -1){
        perror("listen error");
        exit(1);
    }
    int pid=-1;
    int addr_len = sizeof(struct sockaddr_in);
    int max_process_num = 10;
    int i;
    int child_process_status;
    for(i = 0; i< max_process_num; i++){
        if(pid != 0){
            pid = fork();
        }
    }
    if(pid == 0){
        for(;;){
            accept_fd = accept(listen_fd
                                ,(struct sockaddr *)&remote_addr,&addr_len);
            int recv_num;
            for(;;){
                char in_buf[1024];
                memset(in_buf, 0, 1024); 
                recv_num = recv(accept_fd ,&in_buf ,1024 ,0);
                if(recv_num == 0){
                    printf("close socket\n");
                    close(accept_fd);
                    break;
                }
                else{
                    printf("accept:%d:%s\n", recv_num, in_buf);
                }
            }
        }
    }
    else{
        //manager the process
        wait(&child_process_status);
    }
    
    return 0;
}
